import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken, setToken } from '@/utils/auth'
import { getNewToken } from '@/api/user'
import router from '../router'
// create an axios instance
const service = axios.create({
  baseURL: '', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 150000 // request timeout
})
// request拦截器
service.interceptors.request.use(
  config => {
    // 在发送请求之前做些什么
    // 让每个请求携带 token
    config.headers['authorization'] = 'Bearer' + ' ' + getToken('authorization')
    return config
  },
  error => {
    // 处理请求错误
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code === 1 || res.status) {
      return res.data
    } else if (res.code < 1) {
      // 如果请求失败
      Message({
        message: res.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      // console.log(res)
      return Promise.reject(res) 
    }else if (res.code === 200) {
      return res
    }
  },
  error => {
    const { status } = error.response
    if(status == 401){
      MessageBox.alert('账号登录已过期，请重新登录', "提示", {
        confirmButtonText: "确定",
        type: "warning",
        showClose: false,
        showCancelButton: false,
        closeOnClickModal: false,
      })
        .then(() => {
          store.dispatch("user/logout");
          store.dispatch("user/resetToken");
          router.push(`/login`)
        })
        .catch(() => {});
    }
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
